<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="设备列表" name="list">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="设备编号" prop="equipmentNo">
            <el-input
              v-model="queryParams.equipmentNo"
              placeholder="请输入设备编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="设备名称" prop="equipmentName">
            <el-input
              v-model="queryParams.equipmentName"
              placeholder="请输入设备名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['equipment:equipment:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['equipment:equipment:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['equipment:equipment:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['equipment:equipment:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row> -->

        <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
          <el-table-column label="设备编号" align="center" prop="equipmentNo" />
          <el-table-column label="设备名称" align="center" prop="equipmentName" />
          <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['equipment:equipment:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['equipment:equipment:remove']"
              >删除</el-button>
            </template>
          </el-table-column> -->
        </el-table>
        
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>

      <el-tab-pane label="设备类型故障统计" name="statistics">
        <el-card class="box-card">
          <div slot="header">
            <span>设备类型故障统计</span>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              @change="handleDateChange"
              style="float: right; width: 300px;"
            ></el-date-picker>
          </div>
          <div id="failureStatisticsChart" style="width: 100%; height: 400px;" v-loading="chartLoading"></div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加或修改设备清单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备名称" prop="equipmentName">
          <el-input v-model="form.equipmentName" placeholder="请输入设备名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { listEquipment, getEquipment, delEquipment, addEquipment, updateEquipment } from "@/api/equipment/equipment";
import { getFailureStatistics } from "@/api/equipment/analysis";

export default {
  name: "Equipment",
  data() {
    return {
      // 当前激活的标签页
      activeTab: 'list',
      // 日期范围
      dateRange: [],
      // 图表加载状态
      chartLoading: false,
      // 图表实例
      failureStatisticsChart: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备清单表格数据
      equipmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentNo: null,
        equipmentName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.initChart();
  },
  methods: {
    /** 初始化图表 */
    initChart() {
      this.failureStatisticsChart = echarts.init(document.getElementById('failureStatisticsChart'));
      // 监听窗口大小变化，调整图表大小
      window.addEventListener('resize', () => {
        this.failureStatisticsChart && this.failureStatisticsChart.resize();
      });
    },
    /** 日期范围变化 */
    handleDateChange() {
      this.loadFailureStatistics();
    },
    /** 加载故障统计 */
    loadFailureStatistics() {
      if (this.dateRange && this.dateRange.length === 2) {
        this.chartLoading = true;
        const params = {
          startDate: this.dateRange[0],
          endDate: this.dateRange[1]
        };
        getFailureStatistics(params).then(response => {
          const data = response.data;
          if (!data || !data.source || data.source.length === 0) {
            this.$message.warning('所选日期范围内没有数据');
            return;
          }
          
          const option = {
            title: {
              text: '设备类型故障统计',
              left: 'center'
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              formatter: '{b}: {c} 次'
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: data.source.map(item => item['设备类型']),
              axisLabel: {
                interval: 0,
                rotate: 30
              }
            },
            yAxis: {
              type: 'value',
              name: '故障次数',
              nameTextStyle: {
                padding: [0, 0, 0, 40]
              }
            },
            series: [
              {
                name: '故障次数',
                type: 'bar',
                data: data.source.map(item => item['故障次数']),
                itemStyle: {
                  color: '#409EFF'
                },
                label: {
                  show: true,
                  position: 'top'
                }
              }
            ]
          };
          this.failureStatisticsChart.setOption(option);
        }).catch(error => {
          this.$message.error('获取数据失败：' + error.message);
        }).finally(() => {
          this.chartLoading = false;
        });
      } else {
        this.$message.warning('请选择日期范围');
      }
    },
    /** 查询设备清单列表 */
    getList() {
      this.loading = true;
      listEquipment(this.queryParams).then(response => {
        this.equipmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        equipmentNo: null,
        equipmentName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.equipmentNo)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备清单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const equipmentNo = row.equipmentNo || this.ids
      getEquipment(equipmentNo).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备清单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.equipmentNo != null) {
            updateEquipment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEquipment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const equipmentNos = row.equipmentNo || this.ids;
      this.$modal.confirm('是否确认删除设备清单编号为"' + equipmentNos + '"的数据项？').then(function() {
        return delEquipment(equipmentNos);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('equipment/equipment/export', {
        ...this.queryParams
      }, `equipment_${new Date().getTime()}.xlsx`)
    }
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听
    window.removeEventListener('resize', () => {
      this.failureStatisticsChart && this.failureStatisticsChart.resize();
    });
    // 销毁图表实例
    if (this.failureStatisticsChart) {
      this.failureStatisticsChart.dispose();
    }
  }
};
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}
</style>
